﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Configuration;
using System.Security.Cryptography;

namespace Ashwani.Cryptography.Hashing
{
    public class MachineKeyHashProvider : IHashProvider
    {
        enum HashMode
        {
            SHA1,
            MD5,
        }

        HashMode _hashMode = HashMode.SHA1;

        public MachineKeyHashProvider()
        {
            MachineKeySection section;

            if (HostingEnvironment.IsHosted)
            {
                if (HostingEnvironment.ApplicationVirtualPath != null)
                    section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey", HostingEnvironment.ApplicationVirtualPath);
                else
                    section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
            }
            else
            {
                section = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey");
            }

            if (section != null)
            {
                string validation = section.Decryption == null ? string.Empty : section.Validation.ToString().ToLowerInvariant();
                switch (validation)
                {
                    case @"md5":
                        _hashMode = HashMode.SHA1;
                        break;
                }
            }
        }

        public byte[] ComputeHash(byte[] plaintext)
        {
            HashAlgorithm algorithm;
            switch (_hashMode)
            {
                case HashMode.MD5:
                    algorithm = MD5Cng.Create();
                    return new HashCryptographer(algorithm).ComputeHash(plaintext);

                default:
                    algorithm = SHA1Managed.Create();
                    return new HashCryptographer(algorithm).ComputeHash(plaintext);
            }
        }

        

        
        public bool CompareHash(byte[] plaintext, byte[] hashedtext)
        {
            HashAlgorithm algorithm;
            switch (_hashMode)
            {
                case HashMode.MD5:
                    algorithm = MD5Cng.Create();
                    return new HashCryptographer(algorithm).CompareHash(plaintext, hashedtext);
                default:
                    algorithm = SHA1Managed.Create();
                    return new HashCryptographer(algorithm).CompareHash(plaintext, hashedtext);
            }
        }

    }
}
